﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MeshVR;
using Request = MeshVR.AssetLoader.AssetBundleFromFileRequest;
using System.Linq;

namespace PluginIdea
{
    public class EasyDecalManager : Singleton<EasyDecalManager>
    {
        public Dictionary<string, Shader> dic_BundleShaders = new Dictionary<string, Shader>();
        private DynamicDecals decalSystem;

        private bool isInitied;

        public bool IsInitied
        {
            get { return this.isInitied; }
        }

        public bool IsVR
        {
            get { return SuperController.singleton.isOVR || SuperController.singleton.isOpenVR; }
        }

        public void Init(string assetBundlePath)
        {
            if (IsVR)
            {
                SuperController.LogError("don't support VR mode");
                return;
            }

            SuperController.LogMessage(assetBundlePath);
            if (!string.IsNullOrEmpty(assetBundlePath))
            {
                Request request = new Request { path = assetBundlePath, callback = OnAssetBundleLoaded };
                AssetLoader.QueueLoadAssetBundleFromFile(request);
            }
        }

        private void OnAssetBundleLoaded(Request request)
        {
            Shader[] shaders = request.assetBundle.LoadAllAssets<Shader>();
            for (int i = 0; i < shaders.Length; i++)
            {
                SuperController.LogMessage(shaders[i].name);
                if (!dic_BundleShaders.ContainsKey(shaders[i].name))
                {
                    dic_BundleShaders.Add(shaders[i].name, shaders[i]);
                }
            }

            if (decalSystem != null)
            {
                Destroy(decalSystem.gameObject);
            }
            decalSystem = DynamicDecals.System;

            decalSystem.mgr = this;
            isInitied = true;
        }

        new void OnDestroy()
        {
            base.OnDestroy();

            if (decalSystem != null)
            {
                Destroy(decalSystem.gameObject);
            }
        }
    }
}

